package com.easyUploader.entity.factory;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.easyUploader.entity.dao.User;
import com.easyUploader.entity.dto.UserDto;
import com.easyUploader.entity.vo.UserVo;
import com.easyUploader.mapper.UserMapper;
import com.security.domain.authority.CommonUserDetails;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
import java.util.List;

/**
 * @author zdh
 */
public class UserFactory{
    public static final UserConverter USER_CONVERTER= Mappers.getMapper(UserConverter.class);

    @Mapper
    public interface UserConverter {
        @Mappings({
                @Mapping(target = "id",ignore = true),
                @Mapping(target = "score",ignore = true),
                @Mapping(target = "headImg",ignore = true),
                @Mapping(target = "homeDirName",ignore = true),
        })
        User toUser(UserVo userVo);
        @Mappings({
                @Mapping(target = "commonRoles",ignore = true),
                @Mapping(target = "enabled",ignore = true),
                @Mapping(target = "accountNonExpired",ignore = true),
                @Mapping(target = "accountNonLocked",ignore = true),
                @Mapping(target = "credentialsNonExpired",ignore = true)
        })
        UserDto toUserDto(User user);

        @Mappings({
                @Mapping(target = "commonRoles",ignore = true),
                @Mapping(target = "enabled",ignore = true),
                @Mapping(target = "accountNonExpired",ignore = true),
                @Mapping(target = "accountNonLocked",ignore = true),
                @Mapping(target = "credentialsNonExpired",ignore = true)
        })
        List<UserDto> toUserDto(List<User> user);

        default UserDto toUserDto(CommonUserDetails commonUserDetails){
            UserMapper userMapper = SpringUtil.getBean(UserMapper.class);
            User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", commonUserDetails.getUsername()));
            if(user==null){
                return null;
            }
            UserDto userDto = toUserDto(user);
            userDto.setCommonRoles(commonUserDetails.getCommonRoles());
            userDto.setEnabled(commonUserDetails.isEnabled());
            userDto.setAccountNonExpired(commonUserDetails.isAccountNonExpired());
            userDto.setAccountNonLocked(commonUserDetails.isAccountNonLocked());
            userDto.setCredentialsNonExpired(commonUserDetails.isCredentialsNonExpired());
            return userDto;
        }
    }
}
